package base.net.socket
{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	import base.net.socket.events.SocketConnectionEvent;
	import base.net.socket.packet.SocketSendablePacket;
	
	import utils.StringUtil;
	
	public class SocketController extends EventDispatcher
	{
		/**
		 *连接集 
		 */		
		private var _socketConnectionDic:Dictionary=new Dictionary();
		
		public function SocketController()
		{
		}
		
		/**
		 * 执行Socket连接
		 * @param host 主机地址
		 * @param port 主机端口
		 * @param connectionName 连接名称
		 */
		public function connect(host:String, port:int, connectionName:String="default"):void
		{
			if(_socketConnectionDic[connectionName]!=null)
			{
				throw new Error("已存在相同名称的 “"+connectionName+"” SocketConnection。");
				return;
			}
			var socketConnection:SocketConnection=new SocketConnection(host, port);
			socketConnection.addEventListener(SocketConnectionEvent.HANDSHAKE_COMPLETE, __onSocketConnectionEvent);			
			socketConnection.addEventListener(SocketConnectionEvent.CLOSE, __onSocketConnectionEvent);
			socketConnection.addEventListener(SocketConnectionEvent.CONNECTABLE, __onSocketConnectionEvent);
			socketConnection.addEventListener(SocketConnectionEvent.IO_ERROR, __onSocketConnectionEvent);
			socketConnection.addEventListener(SocketConnectionEvent.SECURITY_ERROR, __onSocketConnectionEvent);
			socketConnection.addEventListener(SocketConnectionEvent.RECEIVABLE_PACKET, __onSocketConnectionEvent);			
			_socketConnectionDic[connectionName]=socketConnection;
			socketConnection.connect();
		}
		
		private function __onSocketConnectionEvent(evt:SocketConnectionEvent):void
		{
			dispatchEvent(new SocketConnectionEvent(evt.type, evt.data));
		}
		
		/**
		 *发送数据 
		 * @param socketSendablePacket 发送包
		 * @param connectionName 连接名称
		 */		
		public function sendPacket(socketSendablePacket:SocketSendablePacket, connectionName:String="default"):void
		{
			if(socketSendablePacket)
			{
				var socketConnection:SocketConnection = _socketConnectionDic[connectionName] as SocketConnection;
				if(socketConnection)
				{
					socketConnection.sendPacket(socketSendablePacket);
				}
				else
				{
					throw new Error("指定的 “"+connectionName+"” SocketConnection不存在，无法进行数据发送。");
				}
			}
		}
		
		/**
		 *关闭指定名称的Socket连接 
		 * @param connectionName 连接名称
		 */		
		public function closeSocketConnection(connectionName:String):void
		{
			if(!StringUtil.isEmpty(connectionName))return;
			var socketConnection:SocketConnection = _socketConnectionDic[connectionName] as SocketConnection;
			if(socketConnection)
			{
				socketConnection.close();
				delete _socketConnectionDic[connectionName];
				socketConnection=null;
			}
		}
	}
}